<?php

namespace App;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
	protected $table = "category";
	public $timestamps = false;
	public $fillable = [
		'cname',
		'enname',
		'modelid',
		'pid',
		'isshow',
		'seotitle',
		'seokeyword',
		'seodes',
		'pagestyle',
		'coverpath',
		'listpath',
		'detailpath',
		'content',
		'ordernum'
	];
	//num 1 --
	//num 2 ----
	static function getTree($pid = 0, $num = 0)
	{
		$cols = self::join('models', 'category.modelid', '=', 'models.id')->leftJoin('contentrelation', 'category.id', '=', 'contentrelation.cid')
			->select(DB::raw('count(cms_contentrelation.cid) as content_count'), 'category.*', 'models.namer')
			->where('category.pid', $pid)
			->groupby('category.id')
			->get();
		$arr = [];
		$indentStr = str_repeat('--', $num);
		$num++;
		foreach ($cols as $v) {
			$arr[] = [
				'id' => $v->id,
				'cname' => $v->cname,
				'isshow' => $v->isshow == 1 ? "显示" : '不显示',
				'cnamestr' => $indentStr . $v->cname,
				'pagestyle' => $v->pagestyle == 1 ? '封面' : '列表',
				'modelname' => $v->namer,
				'content_count' => $v->content_count
			];
			$sonArr = self::getTree($v->id, $num);
			$arr = array_merge($arr, $sonArr);
		}
		return $arr;
	}
	static function idToIdStr($id)
	{
		static $idStr;
		if (empty($idStr)) {
			$idStr = $id; //4
		} else {
			$idStr = $id . ">" . $idStr; //3>4
		}
		$ob = self::where('id', $id)->first();
		$fid = $ob->pid;
		if ($fid > 0) {
			//自己调用自己
			self::idToIdStr($fid);
		}
		return ">" . $idStr . ">";
	}

	static function idToNameStr($id)
	{
		static $nameStr;
		$ob = self::where('id', $id)->first();
		if (empty($nameStr)) {
			$nameStr = $ob->cname; //4
		} else {
			$nameStr = $ob->cname . " > " . $nameStr; //3>4
		}

		$fid = $ob->pid;
		if ($fid > 0) {
			//自己调用自己
			self::idToNameStr($fid);
		}
		return $nameStr;
	}
}
